﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Pay.Core;
using Pay.DTO;
using Pay.IService;
using Pay.TO;

namespace Pay.Service {
	public class ProftPayoutService : ServiceBase2, IPayService, IDisposable {
		private IUnitOfWork _iUnitOfWork;
		private ISettingService _iSettingService;
		private IMemberService _iMemberService;
		private IMerchantService _iMerchantService;
		private IChargeService _iChargeService;
		private IRefundService _iRefundService;
		private ITransferService _iTransferService;
		private JwuctSign _jwuctSign;

		public ProftPayoutService(IUnitOfWork iUnitOfWork, ISettingService iSettingService, IMemberService iMemberService,
								   IMerchantService iMerchantService, IChargeService iChargeService, IRefundService iRefundService,
									ITransferService iTransferService) : base(iUnitOfWork) {
			_iUnitOfWork = iUnitOfWork;
			_iSettingService = iSettingService;
			_iMemberService = iMemberService;
			_iMerchantService = iMerchantService;
			_iChargeService = iChargeService;
			_iRefundService = iRefundService;
			_iTransferService = iTransferService;
			_jwuctSign = new JwuctSign();
		}

		#region 扫码的
		/// <summary>
		/// 生成二维码扫码请求通道封装
		/// </summary>
		/// <returns>The pay gateway.</returns>
		/// <param name="obj">Model.</param>
		/// <typeparam name="T">The 1st type parameter.</typeparam>
		public async Task<native_result> NativePay(JObject obj) {
			throw new NotImplementedException();
		}
		#endregion

		#region 支付异步通知－不可用
		/// <summary>
		/// 回调支付通知，商户返回OK，不再回调了，流程是先调用ChargeService的NotifyOrder，
		/// 返回值判断是调用哪个通道，再调用本方法，最后调用ChargeService的Update
		/// </summary>
		/// <returns>The notify.</returns>
		/// <param name="order_no">Order.</param>
		public async Task<string> Notify(string merchant_no, string order_no) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 代付通知－不可用
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="order_no">Order.</param>
		public Task<string> NotifyTransfer(string merchant_no, string order_no) {
			throw new NotImplementedException();
		}
		#endregion

		#region 实名、T0额度-不可用
		/// <summary>
		/// 查询代付T0额度
		/// </summary>
		/// <returns>The quota.</returns>
		/// <param name="merchant_no"></param>
		/// <param name="busiType">0：对公 1：对私</param>
		public Task<quota_result> Quota(string merchant_no, string busiType) {
			throw new NotImplementedException();
		}
		#endregion

		#region 快捷同卡同出-不可用
		/// <summary>
		/// 快捷支付查询
		/// </summary>
		/// <returns>The pay query.</returns>
		/// <param name="model">Model.</param>
		public async Task<pay_notity> QuickPayQuery(refund_model_query model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 快捷支付
		/// </summary>
		/// <returns>The receive.</returns>
		/// <param name="model">Model.</param>
		public async Task<quick_pay_result> QuickPay(quick_pay_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 快捷支付鉴权成功后发短信
		/// </summary>
		/// <returns>The pay resms.</returns>
		/// <param name="model">model.</param>
		public Task<ApiResultMessage> QuickPaySendsms(quick_sendsms_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 确认短信验证码
		/// </summary>
		/// <returns>The pay.</returns>
		/// <param name="model">model.</param>
		public Task<quick_pay_result> QuickPay(quick_sms_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 快捷支付退款
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		public Task<refund_result> QuickPayRefund(refund_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 快捷支付退款查询,并将退款中的单处理为完成
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		public Task<refund_result> QuickPayRefundQuery(refund_model_query model) {
			throw new NotImplementedException();
		}
		#endregion

		#region 网关支付-不可用
		/// <summary>
		/// 网关支付银行
		/// </summary>
		/// <returns>The pay bank.</returns>
		public List<type_setting> GatewayPayBank() {
			var banks = new List<type_setting>();
			banks.Add(new type_setting { value = "BOC", text = "中国银行" });
			banks.Add(new type_setting { value = "ABC", text = "中国农业银行" });
			banks.Add(new type_setting { value = "ICBC", text = "中国工商银行" });
			banks.Add(new type_setting { value = "CCB", text = "中国建设银行" });
			banks.Add(new type_setting { value = "COMM", text = "交通银行" });
			banks.Add(new type_setting { value = "PSBC", text = "中国邮政储蓄银行" });
			banks.Add(new type_setting { value = "CMB", text = "招商银行" });
			banks.Add(new type_setting { value = "CMBC", text = "中国民生银行" });
			banks.Add(new type_setting { value = "CITIC", text = "中信银行" });
			banks.Add(new type_setting { value = "CEB", text = "中国光大银行" });
			banks.Add(new type_setting { value = "HXB", text = "华夏银行" });
			banks.Add(new type_setting { value = "GDB", text = "广发银行" });
			banks.Add(new type_setting { value = "CIB", text = "兴业银行" });
			banks.Add(new type_setting { value = "SPDB", text = "上海浦东发展银行" });
			banks.Add(new type_setting { value = "SPAB", text = "平安银行" });
			banks.Add(new type_setting { value = "SHB", text = "上海银行" });
			banks.Add(new type_setting { value = "BJB", text = "北京银行" });
			banks.Add(new type_setting { value = "HZCB", text = "杭州银行" });
			return banks;
		}

		/// <summary>
		/// 发起网关支付
		/// </summary>
		/// <returns>The receive.</returns>
		/// <param name="model">Model.</param>
		public Task<gateway_pay_result> GatewayPay(gateway_pay_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 网关支付查询
		/// </summary>
		/// <returns>The pay query.</returns>
		/// <param name="model">Model.</param>
		public Task<pay_notity> GatewayPayQuery(refund_model_query model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 网关支付退款
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		public Task<refund_result> GatewayPayRefund(refund_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 网关支付退款查询,并将退款中的单处理为完成
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		public Task<refund_result> GatewayRefundQuery(refund_model_query model) {
			throw new NotImplementedException();
		}
		#endregion

		#region 代付,T+0转账-不可用
		/// <summary>
		/// 单笔代付
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="model">Model.</param>
		public async Task<transfer_result> Transfer(apply_transfer model) {
			_iTransferService.ApplyTransfer2(model);
			return await ApiResultToJson.JsonAsync("提现进行中", new transfer_result {
				order_no = model.order_no, transaction_no = "",
				pay_time = null, status = 4
			});
		}
		public Task<transfer_result> ReTransfer(long id) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 代付批处理:生成文件下载本地，再人工转账。
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="model">Model.</param>
		public async Task<batch_transfer_result> Transfer(batch_transfer model) {
			var dt = DateTime.Now;
			string batchNo = dt.ToString("yyyyMMddHHmmss") + DtoHelper.RandCode(6) + "_" + (int)PayChannel.OutPay;
			string batchFileName = batchNo + ".txt";
			model.batch_file = batchFileName;
			model.batch_no = batchNo;

			//生成代付文件
			string total_row = string.Format("{0},{1},{2},{3},{4},{5}", "订单", "姓名", "身份证", "银行卡号", "银行名称", "提现金额");
			List<string> rows = new List<string>();
			foreach (var item in model.orders) {
				rows.Add(string.Format("{0},{1},{2},{3},{4},{5}", item.order_no, item.account_name, item.id_card,
									   item.account_no, item.bank_name, decimal.Parse(item.tran_amount) / 100));
			}
			try {
				StringBuilder sb = new StringBuilder();
				sb.Append(total_row);
				sb.AppendLine();
				foreach (var row in rows) {
					sb.Append(row);
					sb.AppendLine();
				}
				var fileName = IOHelper.GetMapPath("OutPay", DateTime.Now.ToString("yyyyMMdd"), batchFileName);
				//File.WriteAllText(fileName, sb.ToString(), Encoding.UTF8);
				UTF8Encoding utf8 = new UTF8Encoding(false);
				using (StreamWriter sw = new StreamWriter(fileName, false, utf8)) {
					sw.WriteLine(sb.ToString());
					sw.Close();
					sw.Dispose();
				}
				//商户申请批号写入库
				var batchId = _iTransferService.ApplyTransfer(model);
				return await ApiResultToJson.JsonAsync("文件生成成功", new batch_transfer_result { batch_no = model.batch_no, status = 1 });
			} catch {
				return ApiResultToJson.Json<batch_transfer_result>("文件生成失败");
			}
		}

		/// <summary>
		/// 下载成功后调用
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="batchId">Batch Id.</param>
		public async Task<int> TransferNotify(long batchId, string batchFileName, long merchant_id) {
			var result = _iTransferService.UpdateBatch(batchId, "OutPay", TransferBatchStatus.Notify);
			return result;
		}

		/// <summary>
		/// 提交代付批处理查询，返回回盘文件地址后，进行提现记录更新（平台后台用）
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="batchId">Batch Id.</param>
		/// <param name="noticeTranId">报盘通知交易流水号</param>
		public Task<int> TransferBack(long batchId, string noticeTranId, long merchant_id) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 单笔代付查询
		/// </summary>
		/// <returns>The query.</returns>
		/// <param name="model">Model.</param>
		public Task<transfer_result> TransferQuery(transfer_query model) {
			throw new NotImplementedException();
		}
		#endregion

		#region 代收,T+1转账-不可用
		/// <summary>
		/// 代收签约
		/// </summary>
		/// <returns>The receive.</returns>
		/// <param name="model">Model.</param>
		public Task<ApiResultMessage> InsteadReceive(verify_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 代收签约
		/// </summary>
		/// <returns>The receive.</returns>
		/// <param name="model">Model.</param>
		public Task<ApiResultMessage> InsteadReceive(verify_model_sms model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 单笔代收
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="model">Model.</param>
		public Task<transfer_result> AgencyFund(apply_receive model) {
			throw new NotImplementedException();
		}
		#endregion

		#region 商户进件-不可用
		public Task<merchant_register_result> MerchantRegister(long bind_id) {
			throw new NotImplementedException();
		}

		public Task<merchant_register_result> MerchantModify(long bind_id) {
			throw new NotImplementedException();
		}

		public Task<merchant_register_result> MerchantRegister(verify_auth_model dto, string opt) {
			throw new NotImplementedException();
		}

		public Task<int> ItpToFile(string create_date, int type) {
			throw new NotImplementedException();
		}
		#endregion
	}
}